package com.app.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

/**
 * Created by xinjian.hu on 18-2-12.
 */
@Service
public class ActiveProducerService {
    @Autowired
    private JmsTemplate jmsTemplate;
    private static final Logger logger = LoggerFactory.getLogger(ActiveProducerService.class);

    /**
     * 向默认队列推送消息
     *
     * @param msg
     */
    public void sendMessage(final String msg) {
        String destination = jmsTemplate.getDefaultDestinationName();
        jmsTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
        logger.info(Thread.currentThread().getName() + " 向队列{}发送消息{}", destination, msg);
    }

    /**
     * 向自定义的队列推送消息(方法重载)
     *
     * @param destination
     * @param msg
     */
    public void sendMessage(Destination destination, final String msg) {
        System.out.println(Thread.currentThread().getName() + " 向队列" + destination.toString() + "发送消息---------------------->" + msg);
        jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }
}
